package com.heima.shopweb.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.heima.shopweb.service.MemberFeignService;
import com.zijie.core.util.JsonResult;
import com.zijie.members.model.Members;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/shopping/member")
public class MemberController {
    private MemberFeignService memberFeignService;

    @Autowired
    public void setMemberFeignService(MemberFeignService memberFeignService) {
        this.memberFeignService = memberFeignService;
    }
    @GetMapping("/cart")
    public String cart() {
        return "mall/cart";
    }


    @GetMapping("/login")
    public String login() {
        return "mall/login";
    }
    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JsonResult<Members> login(Members members, Map<String, Object> map, HttpSession session) {
        try {
            String phone = members.getPhone();
            ResponseEntity<JsonResult<Members>> memberByFeign = memberFeignService.findByPhone(phone);

            // 获取返回的 LinkedHashMap 数据
            Object data = memberByFeign.getBody().getData();

            // 使用 Jackson 将 LinkedHashMap 转换为 Members 对象
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JavaTimeModule());
            Members memberLogin = objectMapper.convertValue(data, Members.class);

            session.setAttribute("name", memberLogin.getName());
            session.setAttribute("memberId", memberLogin.getId());

            // 返回 JSON 响应
            JsonResult<Members> result = new JsonResult<>("200", "登录成功", memberLogin);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<>("500", "登录失败: " + e.getMessage(), null);
        }
    }

    //退出功能：前端：点击退出链接时，发送请求到后端并处理响应，后端：清除用户会话并返回成功状态，前端：根据后端响应跳转到登录页面
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //移除用户的会话信息：
        session.removeAttribute("name");
        session.removeAttribute("memberId");
        //返回未登录首页
        return "mall/index";
    }

    //个人中心：
    @GetMapping("/personal")
    public String index(Model model,HttpSession session) {
        //获取当前登录的用户ID：
        Integer memberId =(Integer) session.getAttribute("memberId");
        
        // 检查memberId是否为null
        if (memberId == null) {
            // 如果memberId为null，重定向到登录页面
            return "redirect:/shopping/member/login";
        }
        
        //根据获取到的当前用户的id，调用会员微服务查询当前用户信息：
        ResponseEntity<JsonResult<Members>> memberFeignServiceById =memberFeignService.findById(memberId);
        JsonResult<Members> jr = memberFeignServiceById.getBody();
        if (jr != null && jr.getCode().equals("200")) {
            Members data = jr.getData();
            model.addAttribute("member", data);
        }
        return "mall/personal";
    }

    //修改个人信息：
    @PostMapping("/update")
    @ResponseBody
    public JsonResult<Members> updatePersonalMessage(Members members,HttpSession session){

        ResponseEntity<JsonResult<Members>> responseEntity = memberFeignService.update(members);
        if (responseEntity.hasBody()) {
            JsonResult<Members> result = responseEntity.getBody();
            if (result != null && "200".equals(result.getCode())) {
                if (members.getName()!=null){
                    session.setAttribute("name", members.getName());
                    System.out.println("修改成功");
                }
                return new JsonResult<>("200", "更新成功", result.getData());
            }
        }

        return new JsonResult<>("500", "更新失败", null);
    }
}